<?php /*
Copyright 2002 Dan Boitnott (dboitnot@yahoo.com)

This file is part of phpTasks.

phpTasks is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

phpTasks is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with phpTasks; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/ ?>
<?php
// Global Inits
foreach ($HTTP_GET_VARS as $k => $v) {
	$HTTP_VARS[strtolower($k)] = $v;
}
foreach ($HTTP_POST_VARS as $k => $v) {
	$HTTP_VARS[strtolower($k)] = $v;
}

function std_table($conn, $sql, $hidefields = "", $keyfield="id", $checkboxes = false, $cbprefix = "cb_", $cbheader = "", $checklist = "", $cbbgcolor="white", $showheader = true, $customheader="", $idlinkto = "") {
	// Verify Connection
	if (!$conn) {
		echo("Unable to connect to database!");
		exit;
	}

	// Run Query
	$res = pg_exec($conn, $sql);
	if (!$res) {
		echo("Unable to execute query!");
		exit;
	}

	// Count Fields
	$fc = pg_numfields($res);
	if ($fc > 0) {
		echo ("<table border='0'>");
		if ($showheader) {
			// Generate header
			echo ("<tr class=std_table_header>");
			if ($checkboxes) {
				// Generate checkbox header
				echo ("<td>" . $cbheader . "</td>");
			}
			for ($fnum = 0; $fnum < $fc; $fnum++) {
				if (strpos($hidefields, "," . pg_fieldname($res, $fnum) . ",") === false) {
					echo ("<td>" . pg_fieldname($res, $fnum) . "</td>");
				}
			}
		}
		$rc = pg_numrows($res);

		// Print Out Custom Header
		echo($customheader);

		if ($rc > 0) {
			// Step through rows
			for ($rnum = 0; $rnum < $rc; $rnum++) {
				echo ("<tr bgcolor='silver'>");
				$r = pg_fetch_array($res, $rnum);
				if ($checkboxes) {
					// Generate Check Box
					$rchecked = "";	// Change this
					echo ("<td bgcolor='" . $cbbgcolor . "'><input type=checkbox " . $rchecked . " name='" . $cbprefix . $r[$keyfield] . "'></td>");
				}

				// Step through fields
				for ($fnum = 0; $fnum < $fc; $fnum++) {
					if (strpos($hidefields, "," . pg_fieldname($res, $fnum) . ",") === false) {
						echo ("<td>");
						if ($idlinkto <> "")
							echo ("<a href='" . $idlinkto . $r[$keyfield] . "'>");
						echo ($r[$fnum]);
						if ($idlinkto <> "")
							echo ("</a>");
       						echo ("</td>");
					}
				}

				if ($idlinkto <> "")
					echo ("</a>");
			}
		}
		echo ("</table>");
	}
}

function hasrec($conn, $sql, $retfield = "", $falseval = "") {
	// Verify Connection
	if (!$conn) {
		echo("Unable to connect to database!");
		exit;
	}

	// Run Query
	$res = pg_exec($conn, $sql);
	if (!$res) {
		echo("Unable to execute query!");
		exit;
	}

	if (pg_numrows($res) > 0) {
		if ($retfield <> "") {
			$r = pg_fetch_array($res, 0);
			return $r[$retfield];
		} else
			return true;
  	} else {
		if ($retfield <> "")
			return $falseval;
		else
			return false;
  	}
}

function std_select($conn, $name, $sql, $textfield, $valfield, $val = "", $multiple = false, $size = "1", $extra_options = false, $extras_at_top = true) {
	// Verify Connection
	if (!$conn) {
		echo("Unable to connect to database!");
		exit;
	}

	// Run Query
	$res = pg_exec($conn, $sql);
	if (!$res) {
		echo("Unable to execute query!");
		exit;
	}

	if ($multiple)
		$multiple = " multiple ";
  	else
		$multiple = "";
	echo ("<select name='" . $name . "' size='" . $size . "'" . $multiple . ">");

	// Process Extras
	$extras = "";
	if ($extra_options) {
		foreach ($extra_options as $v => $c) {
			//if (substr($v, 0, 7) == "numeric")
			//	$v = substr($v, 7);
			if ($v == $val)
				$selected = " selected ";
    			else
				$selected = " ";
			$extras .= "<option" . $selected . "value='" . $v . "'>" . $c . "</option>";
		}
	}

	if ($extras_at_top && $extra_options)
		echo ($extras);

	$rc = pg_numrows($res);
	if ($rc > 0) {
		for ($rnum = 0; $rnum < $rc; $rnum++) {
			$r = pg_fetch_array($res, $rnum);
			if ($r[$valfield] == $val)
				$selected = " selected ";
    			else
				$selected = " ";
    			echo ("<option value='" . $r[$valfield] . "'" . $selected . ">" . $r[$textfield] . "</option>");
		}
  	}

	if ((!$extras_at_top) && ($extra_options))
		echo ($extras);

	echo ("</select>");
}

function iif($condition, $trueval, $falseval) {
	if ($condition)
		return $trueval;
  	else
		return $falseval;
}

function redirect($url) {
	header ("Location: " . $url);
	exit;
}

function fetchrow($conn, $table, $where = "", $orderby = "", $dateform = "shortdate") {
	$sql = "SELECT * FROM " . $table;
	if ($where <> "")
		$sql .= " WHERE " . $where;
  	if ($orderby <> "")
		$sql .= " ORDER BY " . $orderby;
  	$res = pg_exec($conn, $sql);
	if (pg_numrows($res) > 0) {
		$ret = get_row($res, 0, $dateform);
	} else
		$ret = false;
  	return $ret;
}

function get_resval($conn, $sql, $field, $dateform = "shortdate") {
	$res = pg_exec($conn, $sql);
	if (pg_numrows($res) > 0) {
		$r = get_row($res, 0, $dateform);
		$ret = $r[$field];
	} else
		$ret = false;
  	return $ret;
}

function get_row($res, $rnum, $dateform="shortdate") {
	if (pg_numrows($res) > $rnum) {
		$r = pg_fetch_array($res, $rnum);
		$fc = pg_numfields($res);
		if ($fc > 0) {
			for ($fnum = 0; $fnum < $fc; $fnum++) {
				$key = pg_fieldname($res, $fnum);
				switch (pg_fieldtype($res, $fnum)) {
				case "bool":
					if ($r[$key] == "t") {
						$r[$key] = true;
     					} else {
						$r[$key] = false;
	     				}
     					break;
         			case "timestamp":
					if ($r[$key]) {
                                	        $ts = strtotime(substr($r[$key],0,19));
						switch ($dateform) {
						case "shortdate":
							$r[$key] = date("n/j/Y", $ts);
							break;
                        	                case "shortdatetime":
                                	                $r[$key] = date("n/j/Y g:ia", $ts);
                                        	        break;
	                                        case "daydatetime":
        	                                        $r[$key] = date("D M j, Y - g:ia", $ts);
                	                                break;
						case "timestamp":
							$r[$key] = $ts;
							break;
	     					case "raw":
							break;
     						default:
							$r[$key] = date($dateform, $ts);
     						}
	          			}
					break;
				}
			}
		}
		return $r;
  	} else
		return $false;
}

function http_logout($redir = "about:blank") {
	$REMOTE_USER = "";
        $REMOTE_PASSWORD = "";
        $PHP_AUTH_USER = "";
        $PHP_AUTH_PW = "";
        header("WWW-Authenticate:Basic Realm=bigred.vinylchloride.com");
}

function html_encode($str) {
        $ret = htmlentities($str);
        $ret = str_replace(chr(13), "<br>", $ret);
        $ret = str_replace("'", "`", $ret);
        $ret = str_replace("  ", "&nbsp;&nbsp;", $ret);
        return $ret;
}

function dump_hash($r) {
	if (is_array($r)) {
		echo ("<table border=1>");
		foreach ($r as $k => $v) {
			echo ("<tr><td align=right><strong>$k</strong></td><td align=left>");
			if (is_array($v))
				dump_hash($v);
    			else
				echo ($v);
			echo ("</td></tr>");
  		}
		echo ("</table>");
  	}
}

function date_ranger($prefix, $valfield, $preset, $start_date=false, $end_date=false, $mode="sql") {
	if (!$start_date)
		$start_date = array("year" => date("Y"), "month" => date("n"), "day" => date("j"));
  	if (!$end_date)
		$end_date = $start_date;
?>
	<table border='0'>
		<tr>
		<td align='left' valign='top'>
			<select name='<?=$prefix?>_preset' onchange="if (<?=$prefix?>_preset.value == 'Date Range') { <?=$prefix?>_daterange.style.display='block'; } else { <?=$prefix?>_daterange.style.display='none'; }">
<?php			switch ($mode) {
			default:
?>
				<option <?=($preset == "Any Day") ? "selected" : "" ?> value="TRUE">Any Day</option>
				<option <?=($preset == "Date Range") ? "selected" : "" ?> value="Date Range">Date Range</option>
				<option <?=($preset == "Today") ? "selected" : "" ?> value="<?=$valfield?>>='<?=date("Y-m-d")?>'">Today</option>
				<option <?=($preset == "This Week") ? "selected" : "" ?> value="<?=$valfield?> BETWEEN '<?=date("Y-m-d", strtotime("-" . date("w") . " day"))?>' AND '<?=date("Y-m-d", strtotime("+" . 6 - date("w") . " day"))?>'">This Week</option>
				<option <?=($preset == "Last Week") ? "selected" : "" ?> value="<?=$valfield?> BETWEEN '<?=date("Y-m-d", strtotime("-1 week -" . date("w") . " day"))?>' AND '<?=date("Y-m-d", strtotime("-1 week +" . 6 - date("w") . " day"))?>'">Last Week</option>
				<option <?=($preset == "This Month") ? "selected" : "" ?> value="EXTRACT(MONTH FROM <?=$valfield?>)=EXTRACT(MONTH FROM NOW()) AND EXTRACT(YEAR FROM <?=$valfield?>)=EXTRACT(YEAR FROM NOW())">This Month</option>
				<option <?=($preset == "Last Month") ? "selected" : "" ?> value="EXTRACT(MONTH FROM <?=$valfield?>)=(EXTRACT(MONTH FROM NOW())-1) AND EXTRACT(YEAR FROM <?=$valfield?>)=EXTRACT(YEAR FROM NOW())">Last Month</option>
				<option <?=($preset == "This Year") ? "selected" : "" ?> value="EXTRACT(YEAR FROM <?=$valfield?>)=EXTRACT(YEAR FROM NOW())">This Year</option>
				<option <?=($preset == "Last Year") ? "selected" : "" ?> value="EXTRACT(YEAR FROM <?=$valfield?>)=EXTRACT(YEAR FROM NOW())-1">Last Year</option>
<?php			} ?>
			</select>
		</td>
		<td id='<?=$prefix?>_daterange' align='left' valign='top' style="display:<?=($preset == "Date Range") ? "block" : "none" ?>">
			<?php date_selector($prefix . "_start", $start_date); ?> to <?php date_selector($prefix . "_end", $end_date); ?>
		</td>
		</tr>
  	</table>
<?php
}

function date_selector($prefix, $value = false) {
	if (!$value)
		$value = array("year" => date("Y"), "month" => date("n"), "day" => date("j"));
	echo ("<select name='" . $prefix . "_month'>");
	for ($x = 1; $x <= 12; $x++) {
		$selected = (($x == $value["month"]) ? " selected " : "");
		echo ("<option" . $selected . " value='$x'>" . date("F", mktime(0, 0, 0, $x, 1, 2000)) . "</option>");
	}
	echo ("</select>");
	echo ("<input type=text size=3 name='" . $prefix . "_day' value='" . $value["day"] . "'>");
	echo ("<input type=text size=5 name='" . $prefix . "_year' value='" . $value["year"] . "'>");
}

function html_calendar($name, $month, $year, $ret_url, $events = false) {
	$events = array(12 => "St. Whiskypants Day");
?>
	<table border='1'><tr><td><table border='0'><tr>
		<td align='center' valign='bottom'><small><strong>Sun</strong></small></td>
		<td align='center' valign='bottom'><small><strong>Mon</strong></small></td>
		<td align='center' valign='bottom'><small><strong>Tue</strong></small></td>
		<td align='center' valign='bottom'><small><strong>Wed</strong></small></td>
		<td align='center' valign='bottom'><small><strong>Thu</strong></small></td>
		<td align='center' valign='bottom'><small><strong>Fri</strong></small></td>
		<td align='center' valign='bottom'><small><strong>Sat</strong></small></td>
  	</tr><tr>
<?php
	$dow = date("w",mktime(0, 0, 0, $month, 1, $year));
	while ($dow > 0) {
		echo ("<td></td>");
		$dow--;
	}
	for ($d = 1; checkdate($month, $d, $year); $d++) {
		$dow = date("w",mktime(0, 0, 0, $month, $d, $year));
		if ($dow == 0 || $dow == 6)
			$bgcolor = "gray";
   		else
			$bgcolor = "silver";
		echo ("\n<td align='left' valign='top' bgcolor='$bgcolor'><small><strong>$d</strong>");
		if (isset($events[$d])) {
			echo ("<br>");
			echo ($events[$d]);
		}
		echo ("</small></td>");
		if ($dow == 6 && checkdate($month, $d+1, $year))
			echo ("</tr><tr>");
	}
	echo ("</table></td></tr></table>");
}

function get_holidays($day, $month, $year, $del = "<br>") {
	$dow = get_dayofweek($day, $month, $year);
	$cod = 0;
	for ($x = 1; $x <= $day; $x++) {
		if (get_dayofweek($x, $month, $year) == $dow)
			$cod++;
  	}
	$ret = "";
	switch($month) {
	case 1:
		break;
	case 2:
		if ($dow == 1 && $cod == 3)
			$ret .= (($ret != "") ? $del : "") . "President's Day";
		break;
	case 3:
		break;
	case 4:
		if ($dow == 1 && $cod == 3)
			$ret .= (($ret != "") ? $del : "") . "Patriot's Day";
		break;
	case 5:
		break;
	case 6:
		break;
	case 7:
		if ($day == 4)
			$ret .= (($ret != "") ? $del : "") . "Independence Day";
		break;
	case 8:
		break;
	case 9:
		break;
	case 10:
		break;
	case 11:
		break;
	case 12:
		switch($day) {
		case 15:
			$ret .= (($ret != "") ? $del : "") . "Bill of Rights Day";
			break;
		case 21:
			$ret .= (($ret != "") ? $del : "") . "Forefather's Day";
			break;
   		}
		break;
	}
	return $ret;
}

function get_dayofweek($day, $month, $year) {
	return date("w", mktime(0, 0, 0, $month, $day, $year));
}

function parse_config_file($filename, $defaults = false) {
	if ($defaults) {
		foreach ($defaults as $k => $v) {
			$ret[strtolower($k)] = $v;
		}
	}
	if (is_file($filename)) {
		$lines = file($filename);
		while (list($lnum, $line) = each($lines)) {
			$line = trim($line);
			if (substr($line, 0, 1) != "#") {
				list($k, $v) = preg_split("/[\s=]+/", $line);
				$ret[strtolower($k)] = $v;
	   		}
		}
  	}
	return $ret;
}

function reserve_sequence($conn, $seq) {
	$sql = "SELECT NEXTVAL('$seq')";
	return get_resval($conn, $sql, "nextval");
}
?>
